package com.shine.chemicalWholeProcessSystem.ui.hiddenTroubleInvestigation;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.ImageViewerPopupView;
import com.lxj.xpopup.enums.PopupType;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.interfaces.OnSrcViewUpdateListener;
import com.lxj.xpopup.interfaces.XPopupImageLoader;
import com.shine.chemicalWholeProcessSystem.BR;
import com.shine.chemicalWholeProcessSystem.R;
import com.shine.chemicalWholeProcessSystem.app.ChooseData;
import com.shine.chemicalWholeProcessSystem.app.Constants;
import com.shine.chemicalWholeProcessSystem.base.BaseActivity;
import com.shine.chemicalWholeProcessSystem.bean.DictionariesBean;
import com.shine.chemicalWholeProcessSystem.bean.RiskManagementBean;
import com.shine.chemicalWholeProcessSystem.databinding.ActivityHiddenTroubleInvestigationCreateBinding;
import com.shine.chemicalWholeProcessSystem.databinding.ActivityRiskManagementCreateBinding;
import com.shine.chemicalWholeProcessSystem.http.ApiException;
import com.shine.chemicalWholeProcessSystem.http.ECHttpResponse;
import com.shine.chemicalWholeProcessSystem.http.ECObserver;
import com.shine.chemicalWholeProcessSystem.http.RetrofitClient;
import com.shine.chemicalWholeProcessSystem.http.RxUtils;
import com.shine.chemicalWholeProcessSystem.http.Service;
import com.shine.chemicalWholeProcessSystem.ui.adapter.ImageAdapter;
import com.shine.chemicalWholeProcessSystem.ui.riskManagement.RiskManagementCreateViewModel;
import com.shine.chemicalWholeProcessSystem.utils.SPUtils;
import com.youth.banner.loader.ImageLoader;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

import cn.bingoogolapple.baseadapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.baseadapter.BGAOnRVItemClickListener;

public class HiddenTroubleInvestigationCreateActivity extends BaseActivity<ActivityHiddenTroubleInvestigationCreateBinding, HiddenTroubleInvestigationCreateViewModel> {
    private static final int REQUEST_CODE_PHOTO = 10001;
    private ArrayList<Object> sceneImgList = new ArrayList<>();
    private ArrayList<Object> rectificationImgList = new ArrayList<>();
    private ImageAdapter sceneImageAdapter, rectificationImageAdapter;
    private boolean chooseImgType;//true:现场 ，false : 整改
    private List<LocalMedia> localMediaList = new ArrayList<>();
    private List<LocalMedia> rectificationMediaList = new ArrayList<>();

    private boolean isEdit;
    private String id;
    private List<String> dataStrList = new ArrayList<>();

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_hidden_trouble_investigation_create;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HiddenTroubleInvestigationCreateViewModel initViewModel() {
        return new HiddenTroubleInvestigationCreateViewModel(this);
    }

    @Override
    public int appTheme() {
        return Constants.THEME_FULL;
    }

    @Override
    public void initData() {
        super.initData();
        setStatusBar();
        initTitle(this, "检查隐患");

        isEdit = getIntent().getBooleanExtra(Constants.BUNDLE_EDIT, false);

        if (isEdit) {
            showView((RiskManagementBean) getIntent().getSerializableExtra(Constants.BUNDLE_EXTRA));
            binding.add.setText("确  认  编  辑");
        } else {
            binding.add.setText("确  认  添  加");
        }

        binding.sceneRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        sceneImageAdapter = new ImageAdapter(binding.sceneRecyclerView, R.layout.item_add_img);
        binding.sceneRecyclerView.setAdapter(sceneImageAdapter);

        sceneImageAdapter.setOnItemChildClickListener(new BGAOnItemChildClickListener() {
            @Override
            public void onItemChildClick(ViewGroup parent, View childView, int position) {
                sceneImageAdapter.removeItem(position);
            }
        });

        sceneImageAdapter.setOnRVItemClickListener(new BGAOnRVItemClickListener() {
            @Override
            public void onRVItemClick(ViewGroup parent, View itemView, int position) {
                new XPopup.Builder(HiddenTroubleInvestigationCreateActivity.this)
                        .isDestroyOnDismiss(true)
                        .asImageViewer(itemView.findViewById(R.id.img), position, sceneImgList,
                                null,new ImageLoader())
                        .show();
            }
        });

        binding.rectificationRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        rectificationImageAdapter = new ImageAdapter(binding.rectificationRecyclerView, R.layout.item_add_img);
        binding.rectificationRecyclerView.setAdapter(rectificationImageAdapter);

        rectificationImageAdapter.setOnItemChildClickListener(new BGAOnItemChildClickListener() {
            @Override
            public void onItemChildClick(ViewGroup parent, View childView, int position) {
                rectificationImageAdapter.removeItem(position);
            }
        });

        rectificationImageAdapter.setOnRVItemClickListener(new BGAOnRVItemClickListener() {
            @Override
            public void onRVItemClick(ViewGroup parent, View itemView, int position) {
                new XPopup.Builder(HiddenTroubleInvestigationCreateActivity.this)
                        .isDestroyOnDismiss(true)
                        .asImageViewer(itemView.findViewById(R.id.img), position, rectificationImgList,
                                null,new ImageLoader())
                        .show();
            }
        });

        binding.inspectionDate.setOnClickListener(this);
        binding.responsibleDepartment.setOnClickListener(this);
        binding.hazardCategory.setOnClickListener(this);
        binding.plannedCompletionTime.setOnClickListener(this);
        binding.actualCompletionTime.setOnClickListener(this);
        binding.rectificationPerson.setOnClickListener(this);
        binding.hiddenDangerLevel.setOnClickListener(this);
        binding.processingStatus.setOnClickListener(this);


        binding.sceneUpload.setOnClickListener(this);
        binding.sceneDownload.setOnClickListener(this);
        binding.scenePreview.setOnClickListener(this);
        binding.rectificationUpload.setOnClickListener(this);
        binding.rectificationDownload.setOnClickListener(this);
        binding.rectificationPreview.setOnClickListener(this);

        sceneImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");
        sceneImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");
        sceneImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");
        sceneImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");

        rectificationImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");
        rectificationImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");
        rectificationImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");
        rectificationImgList.add("https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF");


        sceneImageAdapter.addNewData(sceneImgList);
        rectificationImageAdapter.addNewData(rectificationImgList);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.inspectionDate:
                Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        binding.inspectionDate.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
                        .show();
                break;
            case R.id.plannedCompletionTime:
                Calendar calendar1 = Calendar.getInstance();
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        binding.plannedCompletionTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                    }
                }, calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH))
                        .show();
                break;
            case R.id.actualCompletionTime:
                Calendar calendar2 = Calendar.getInstance();
                new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        binding.actualCompletionTime.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
                    }
                }, calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH))
                        .show();
                break;
            case R.id.responsibleDepartment:

                break;
            case R.id.hazardCategory:
                getDictionaries(0);
//                showBottomPop(0, ChooseData.hazardCategoryList());
                break;
            case R.id.rectificationPerson:
                break;
            case R.id.hiddenDangerLevel:
                getDictionaries(1);
//                showBottomPop(1, ChooseData.hiddenDangerLevelList());
                break;
            case R.id.processingStatus:
                getDictionaries(2);
//                showBottomPop(2, ChooseData.processingStatusList());
                break;
            case R.id.sceneUpload:
                chooseImgType = true;
                PictureSelector.create(HiddenTroubleInvestigationCreateActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .isCamera(true)
                        .isGif(false)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(REQUEST_CODE_PHOTO);
                break;
            case R.id.sceneDownload:
                localMediaList.clear();
                for (Object imgUrl : sceneImgList) {
                    localMediaList.add(new LocalMedia((String) imgUrl, 0, 0, null));
                }
                PictureSelector.create(this).externalPicturePreview(0, localMediaList);
                break;
            case R.id.scenePreview:
                new XPopup.Builder(HiddenTroubleInvestigationCreateActivity.this)
                        .isDestroyOnDismiss(true)
                        .asImageViewer(null, 0, sceneImgList,
                                null,new ImageLoader())
                        .show();
                break;
            case R.id.rectificationUpload:
                chooseImgType = false;
                PictureSelector.create(HiddenTroubleInvestigationCreateActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .isCamera(true)
                        .isGif(false)
                        .selectionMode(PictureConfig.SINGLE)
                        .forResult(REQUEST_CODE_PHOTO);
                break;
            case R.id.rectificationDownload:
                rectificationMediaList.clear();
                for (Object imgUrl : rectificationImgList) {
                    rectificationMediaList.add(new LocalMedia((String) imgUrl, 0, 0, null));
                }
                PictureSelector.create(this).externalPicturePreview(0, rectificationMediaList);
                break;
            case R.id.rectificationPreview:
                new XPopup.Builder(HiddenTroubleInvestigationCreateActivity.this)
                        .isDestroyOnDismiss(true)
                        .asImageViewer(null, 0, rectificationImgList,
                                null,new ImageLoader())
                        .show();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_PHOTO) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                if (selectList != null && selectList.size() > 0) {
                    if (chooseImgType) {
                        sceneImgList.add(selectList.get(0).getPath());
                        sceneImageAdapter.addLastItem(selectList.get(0).getPath());
                    } else {
                        rectificationImgList.add(selectList.get(0).getPath());
                        rectificationImageAdapter.addLastItem(selectList.get(0).getPath());
                    }
//                    Glide.with(this).load(selectList.get(0).getPath()).into(binding.img);
//                    uploadFile(selectList.get(0).getPath(), imgType);
                }
            }
        }
    }


    private void showView(RiskManagementBean bean) {
        id = bean.getId();

    }

    private void getDictionaries(int type) {
        //风险分类(RiskClass)
        String typeStr = "";
        switch (type) {
            case 0:
                typeStr = "yhlb";
                break;
            case 1:
                typeStr = "yhdj";
                break;
            case 2:
                typeStr = "clzt";
                break;
            default:
                break;
        }

        showLoading("");
        RetrofitClient.getInstance().create(Service.class)
                .details(typeStr, SPUtils.getInstance().getString(Constants.SP_TOKEN), SPUtils.getInstance().getString(Constants.SP_MARK))
                .compose(RxUtils.<ECHttpResponse<List<DictionariesBean>>>bindToLifecycle(this))
                .compose(RxUtils.<ECHttpResponse<List<DictionariesBean>>>schedulersTransformer())
                .compose(RxUtils.<ECHttpResponse<List<DictionariesBean>>>exceptionTransformer())
                .subscribe(new ECObserver<List<DictionariesBean>>() {
                    @Override
                    protected void _onNext(List<DictionariesBean> dictionariesBeanList) {
                        dismissLoading();
                        dataStrList.clear();
                        for (DictionariesBean dictionariesBean : dictionariesBeanList) {
                            dataStrList.add(dictionariesBean.getF_ItemName());
                        }
                        showBottomPop(type, dataStrList, dictionariesBeanList);
                    }

                    @Override
                    protected void _onError(ApiException ex) {
                        ToastMessage(ex.message);
                        dismissLoading();
                    }
                });
    }


    private String[] data = null;

    private void showBottomPop(int type, List<String> dataList, List<DictionariesBean> dictionariesBeanList) {
        data = dataList.toArray(new String[0]);

        new XPopup.Builder(HiddenTroubleInvestigationCreateActivity.this)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .maxHeight(1000)
                .asBottomList("请选择一项", data,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int positionInt, String text) {
                                switch (type) {
                                    case 0:
                                        binding.hazardCategory.setText(data[positionInt]);
//                                        bean.setRiskClass(dictionariesBeanList.get(positionInt).getF_ItemValue());
                                        break;
                                    case 1:
                                        binding.hiddenDangerLevel.setText(data[positionInt]);
                                        break;
                                    case 2:
                                        binding.processingStatus.setText(data[positionInt]);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        })
                .show();
    }


    public static class ImageLoader implements XPopupImageLoader {
        @Override
        public void loadImage(int position, @NonNull Object url, @NonNull ImageView imageView) {
            //必须指定Target.SIZE_ORIGINAL，否则无法拿到原图，就无法享用天衣无缝的动画
//            Glide.with(imageView).load(url).into(imageView);
            Glide.with(imageView).load(url).apply(new RequestOptions().override(Target.SIZE_ORIGINAL)).into(imageView);
        }
        @Override
        public File getImageFile(@NonNull Context context, @NonNull Object uri) {
            try {
                return Glide.with(context).downloadOnly().load(uri).submit().get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    }
}
